﻿/**
  *@brief 结构体序列化往往跟通信协议报文有关，所以我将MQTT协议的RemainingLength
  *       (剩余长度)编解码方式放在本类中
*/
#ifndef STRUCTSERIALIZE_H
#define STRUCTSERIALIZE_H

#include <vector>
#include <string>
#include <iostream>
using namespace std;
#define StructFieldSize(MyStruct,MyField) sizeof(((MyStruct*)0)->MyField)
#define StructFieldOffset(MyStruct,MyField) (size_t)&(((MyStruct*)0)->MyField)
#define StructHeaderPoint(MyStruct,MyField,MyFieldPointer) (MyFieldPointer != 0 ? (MyStruct *)((char *)MyFieldPointer - StructFieldOffset(MyStruct,MyField)) : 0) //通过结构体字段地址获取结构体地址
typedef unsigned char BYTE;


typedef struct _XiaomiMobileProduct
{
   int i;
   vector<string> v;

   int Serialize(BYTE *apData)
   {
       BYTE *lpData = apData;
       *(int*)lpData = i;
       lpData += sizeof(int);

       int liVecLen = (int)v.size();
       *(int*)lpData = liVecLen;
       lpData += sizeof(int);
       for(int n = 0; n < liVecLen; ++ n)
       {
           int liLen = v[n].length();
           *(int*)lpData = liLen;
           lpData += sizeof(int);
           memcpy(lpData, v[n].c_str(), liLen);
           lpData += liLen;
       }
       return lpData-apData;
   }

}XiaomiMobileProduct;

class StructSerialize
{
public:
    StructSerialize();
    void test();
    void printStringSizeof();
    void Decode(unsigned int tmp[],int nLen);
    void Encode(unsigned int nInput);
};

#endif // STRUCTSERIALIZE_H
